using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Web;
using iPhOwa.Exchange.ContentClasses;
using iPhOwa.Exchange.Managers;
using iPhOwa.Web.Properties;

namespace iPhOwa.Web.Controls
{
	/// <summary>
	/// Display content for a mailbox folder.
	/// </summary>
	public partial class FolderContent : iPhOwaControl
	{
		/// <summary>
		/// Flag to determine if we show the "From" or "To" line in the listing.
		/// </summary>
		protected bool showTo;

		[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Int32.TryParse(System.String,System.Int32@)")]
		private int PageNumber
		{
			get
			{
				int page;

				int.TryParse(Request["page"], out page);

				return page;
			}
		}

		/// <summary>
		/// Page Load event.
		/// </summary>
		[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
		protected void Page_Load(object sender, EventArgs e)
		{
			int startItem = Settings.Default.MaxItemsPerPage * PageNumber;
			int endItem = startItem + Settings.Default.MaxItemsPerPage - 1;

			Folder currentFolder = FolderManager.Get(Path, OwaSession);

			if(currentFolder == null)
			{
				throw new ApplicationException("Current folder is null!");
			}

			if(string.Compare(currentFolder.DisplayName, "Sent Items", StringComparison.InvariantCultureIgnoreCase) == 0)
			{
				showTo = true;
			}

			ICollection<Item> items = ItemManager.GetList(Path, startItem, endItem, OwaSession);

			fl.DataSource = items;
			fl.DataBind();
			fl.Visible = pp.Visible = items.Count > 0;
			np.Visible = items.Count == 0;
			pl.Visible = PageNumber > 0;
			nl.Visible = items.Count == Settings.Default.MaxItemsPerPage;
			pp.Visible = pl.Visible || nl.Visible;
			pl.NavigateUrl = string.Format(CultureInfo.InvariantCulture, "../?path={0}&page={1}"
			                               , HttpUtility.UrlEncode(currentFolder.Href.ToString()), PageNumber - 1);
			nl.NavigateUrl = string.Format(CultureInfo.InvariantCulture, "../?path={0}&page={1}"
			                               , HttpUtility.UrlEncode(currentFolder.Href.ToString()), PageNumber + 1);
		}
	}
}